﻿using System;
using System.Collections.Generic;
using System.Linq;
using Cjc.ExpressionEngine.Excel.Runtime.Operations;
using Microsoft.Scripting.Runtime;
using Cjc.ExpressionEngine.Excel.Runtime.Binding;
using Cjc.ExpressionEngine.Excel.Runtime.Types;

namespace Cjc.ExpressionEngine.Excel.Runtime
{
	public static class ExcelHelpers
	{
		public static object Sum( CodeContext context, params decimal[] values )
		{
			return Int32Ops.Reduce( values.Sum() );
		}

		public static object Sum( CodeContext context, Range range )
		{
			var scope = context.Scope as ExcelScope;

			return Sum( context, range.GetCells( scope.Worksheet ) );
		}

		public static object Sum( CodeContext context, IEnumerable<Cell> values )
		{
			var scope = context.Scope as ExcelScope;
			var operations = scope.Worksheet.Operations;

			return Int32Ops.Reduce( values.Where( v => v.Value != null ).Aggregate(
				(object)(decimal)0,
				( v, c ) => operations.Add( v, c.Value ) ) );
		}

		public static double Exp( CodeContext context, double d ) { return Math.Exp( d ); }
		public static decimal Abs( CodeContext context, decimal d ) { return Math.Abs( d ); }
		public static double Pow( CodeContext context, double x, double y ) { return Math.Pow( x, y ); }
		public static DateTime Today( CodeContext context ) { return DateTime.Today; }

		public static decimal Min( CodeContext context, decimal x, decimal y ) { return Math.Min( x, y ); }
		public static decimal Max( CodeContext context, decimal x, decimal y ) { return Math.Max( x, y ); }

		public static object CalcLookup( CodeContext context, object lookupValue, string tableName, string column, bool closest )
		{
			var scope = context.Scope as ExcelScope;

//			scope.Worksheet.
			return 42;
		}
	}
}